<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-form toolbar">
            角色名称
            <input id="roleName" class="layui-input search-input" type="text" placeholder="角色名称"/>&emsp;
            <button id="role-btn-search" class="layui-btn layui-btn-normal layui-btn-sm icon-btn"><i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button id="role-btn-add" class="layui-btn layui-btn-normal layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加
            </button>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" id="role-table" lay-filter="role-table"></table>
    </div>
</div>

<!-- 表单弹窗 -->
<script type="text/html" id="role-model">
    <div  style="height: 450px;overflow-y:auto;">
        <form id="role-form" lay-filter="role-form" class="layui-form model-form">
            <input name="roleId" type="hidden"/>
            <div class="layui-form-item">
                <label class="layui-form-label required">角色名</label>
                <div class="layui-input-block">
                    <input name="roleName" placeholder="请输入角色名" type="text" class="layui-input layui-input-sm" maxlength="20"
                           lay-verify="required" required/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">角色标识</label>
                <div class="layui-input-block">
                    <input name="roleCode" id="roleCode" placeholder="角色标识" type="text" class="layui-input layui-input-sm"
                           maxlength="20"
                           lay-verify="required" required/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色描述</label>
                <div class="layui-input-block">
                    <input name="roleDesc" placeholder="角色描述" type="text" class="layui-input layui-input-sm" maxlength="100"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">平台</label>
                <div class="layui-input-block ">
                    <input type="hidden" name="clientId" id="clientId">
                    <select name="debugfield" id="client" lay-verify="required" lay-filter="client"
                            placeholder="平台"></select>
                </div>
            </div>
            <div id="tree"></div>
            <div class="layui-form-item model-form-footer">
                <button class="layui-btn layui-btn-normal" ew-event="closeDialog" type="button">取消</button>
                <button class="layui-btn" lay-filter="role-form-submit" lay-submit>保存</button>
            </div>
        </form>
    </div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="role-table-bar">
    {{#  if(d.isSystem ==0){ }}
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{#  } }}
    <a class="layui-btn layui-btn-xs" lay-event="setuser">分配用户</a>
</script>

<!--给角色分配用户-->
<script type="text/html" id="app-modelList">
    <form id="app-fromList" lay-filter="app-fromList" class="layui-form model-form">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                查询：<input id="app-edit-search1" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
                <button class="layui-btn icon-btn layui-btn-normal layui-btn-sm"
                        data-method="queryAppModelList">
                    <i class="layui-icon">&#xe615;</i>搜索
                </button>
            </div>
            <!-- 数据表格 -->
            <table class="layui-table" id="app-from" lay-filter="app-from"></table>
        </div>
    </form>
</script>

<script>
    var menthods;
    layui.use(['form', 'table', 'util', 'tools', 'config', 'tree'], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        var tools = layui.tools;
        var tree = layui.tree;
        var $ = layui.$;
        var tempRoleId;
        var saveOrUpdateMenthod = 'post';
        menthods = {
            //初始化下拉列表
            initClientList: res => {
                tools.request({url: '/plm/client/dropdown', method: 'get'}).done(res => {
                    var data = res.data;
                    if (data && data.length > 0) {
                        var html = '<option value="' + $("#clientId").val() + '">' + $("#clientId").val() + '</option>';
                        for (var i in data) {
                            html += '<option value="' + data[i].clientId + '">' + data[i].name + '</option>';
                        }
                        $("#client").html(html);
                        form.render('select');
                    }
                });
            },
            //初始化数据表格
            initDataTable() {
                //渲染表格
                table.render({
                    elem: '#role-table',
                    url: config.base_server + '/plm/role/page',
                    page: true,
                    cols: [[
                        {type: 'numbers', title: '序号'},
                        {field: 'roleId', hide: true, title: 'ID', width: 80},
                        {field: 'roleName', title: '角色名'},
                        {field: 'roleCode', title: '角色代码'},
                        {field: 'roleDesc', title: '说明'},
                        {field: 'clientId', title: '客户端'},
                        {
                            field: 'isSystem', title: '是否内置角色', templet: (res => {
                                return res.isSystem == 1 ? '是' : "否";
                            })
                        },
                        {
                            field: 'createTime', sort: true, templet: function (d) {
                                return util.toDateString(d.createTime);
                            }, title: '创建时间'
                        },
                        {align: 'center', toolbar: '#role-table-bar', title: '操作', width: 250}
                    ]]
                });
                menthods.initClientList();
            },
            //所有监听事件
            on() {
                // 表单提交事件
                form.on('submit(role-form-submit)', function (data) {
                    tools.request({
                        url: '/plm/api/role',
                        method: saveOrUpdateMenthod,
                        params: data.field
                    }).done(function (res) {
                        if (res.code == 0) {
                            menthods.saveRoleMenuData(res.data == null ? data.field.roleId : res.data.roleId);
                            layer.msg(res.msg, {icon: 1, time: 500});
                            table.reload('role-table');
                            layer.closeAll('page');
                        } else {
                            layer.msg(res.msg, {icon: 2, time: 500});
                        }
                    });
                    return false;
                });

                //监听平台选择
                form.on('select(client)', res => {
                    $("#clientId").val(res.value);
                    //加载菜单信息
                    if (res.value) {
                        menthods.getMenuTreeData(tempRoleId, res.value);
                    } else {
                        menthods.getMenuTreeData(tempRoleId, 'asdf');
                    }
                });

                // 工具条点击事件
                table.on('tool(role-table)', function (obj) {
                    var data = obj.data;
                    if (obj.event === 'edit') { //修改
                        menthods.showEditModel(data);
                        tempRoleId = data.roleId;
                        saveOrUpdateMenthod = 'put';
                        menthods.getMenuTreeData(tempRoleId, data.clientId);
                    } else if (obj.event === 'del') { //删除
                        menthods.doDelete(obj);
                    } else if (obj.event === 'menu') {  // 菜单管理
                        menthods.showMenuDialog(obj.data.roleId, obj.data.clientId);
                    } else if (obj.event === 'setuser') {  // 权限管理
                        menthods.showEmployeeMode(obj.data);
                    }
                });
                // 添加按钮点击事件
                $('#role-btn-add').click(function () {
                    menthods.showEditModel();
                    tempRoleId = -1;
                    saveOrUpdateMenthod = 'post';
                });
            },
            //显示编辑
            showEditModel(data) {
                menthods.initDataTable();
                layer.open({
                    type: 1,
                    title: data ? '修改角色' : '添加角色',
                    area: ['600px', '500px'],
                    offset: '120px',
                    content: $('#role-model').html(),
                    success: res => {
                        $('#role-form')[0].reset();
                        $('#role-form').attr('method', 'POST');
                        if (data) {
                            //时禁用这些选项
                            $("#roleCode").attr("readonly", "readonly")
                            $("#client").attr("disabled", "disabled")
                            form.render('select');
                            form.val('role-form', data);
                            $('#role-form').attr('method', 'POST');
                        }
                    }
                });
            },
            //删除
            doDelete(obj) {
                layer.confirm('确定要删除吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    tools.request({
                        url: '/plm/api/role/' + obj.data.roleId,
                        method: 'DELETE'
                    }).done(function (res) {
                        layer.closeAll('loading');
                        if (res.code == 0) {
                            layer.msg(res.msg, {icon: 1, time: 500});
                            obj.del();
                        } else {
                            layer.msg(res.msg, {icon: 2, time: 500});
                        }
                    });
                });
            },
            //获取菜单树的方法
            getMenuTreeData(roleId, clientId) {
                tools.request({url: '/plm/menu/tree/' + roleId, method: 'get'}).done(res => {
                    var checkedIds = res.data;
                    tools.request({
                        url: '/plm/menu/treeByClientId/' + clientId,
                        method: 'get'
                    }).done(result => {
                        menthods.initTree(result.data);
                        tree.setChecked('demo', checkedIds);
                    });
                })
            },
            //保存角色绑定的菜单
            saveRoleMenuData(roleId) {
                var checkData = tree.getChecked('demo');
                var treeMenuIds = menthods.getTreeMenuIds(checkData, []);
                var param = "?roleId=" + roleId + "&menuIds=" + treeMenuIds.join(",");
                tools.request({url: '/plm/api/role/updateRoleMenu' + param, method: 'put'}).done(res => {
                    if (res.data) {
                        layer.msg('保存菜单信息成功', {icon: 1, time: 500});
                    } else {
                        layer.msg('保存菜单信息失败', {icon: 2, time: 500});
                    }
                })
            },
            //初始化菜单树
            initTree(data) {
                tree.render({
                    elem: '#tree', //绑定元素
                    id: 'demo',
                    accordion: false, //是否开启手风琴
                    showCheckbox: true, //是否显示复选框
                    showLine: true,//不显示虚线
                    data: menthods.changeToTreeData(data)
                });
            },
            //修改获取服务器的菜单数据
            changeToTreeData(data) {
                var menus = data.menus;
                menthods.setMenuTitle(menus);
                return menus;
            },
            setMenuTitle(menus) {
                for (var m in menus) {
                    var menu = menus[m];
                    menu.title = menu.name;
                    if (menu.children.length > 0) {
                        menthods.setMenuTitle(menu.children);
                    }
                }
            },
            //获取选中的菜单树的ID
            getTreeMenuIds(list, ids) {
                if (list) {
                    for (var l in list) {
                        var tempObj = list[l];
                        ids.push(tempObj.id);
                        if (tempObj.children.length > 0) {
                            menthods.getTreeMenuIds(tempObj.children, ids);
                        }
                    }
                }
                return ids;
            },
            //显示分配角色框框
            showEmployeeMode(data) {
                var title = "分配角色";
                layer.open({
                    type: 1,
                    title: title,
                    area: '800px',
                    offset: '150px',
                    content: $('#app-modelList').html(),
                    btn: ['保存', '关闭'],
                    success: function () {
                        // 渲染表格
                        table.render({
                            elem: '#app-from',
                            url: config.base_server + '/plm/api/employee/listByRole?roleId=' + data.roleId,
                            method: 'GET',
                            page: true,
                            cols: [[
                                {
                                    field: 'isRole', templet: (res => {
                                        return '<div class="center"><input type="checkbox" value="' + res.userId + '" class="app-from-roleIds" lay-skin="primary" ' + (res.isRole == 1 ? "checked" : "") + '></div>'
                                    })
                                },
                                {field: 'no', title: '编号'},
                                {field: 'name', title: '姓名'},
                                {field: 'phone', title: '电话'},
                            ]]
                        });
                    },
                    yes: index => {
                        var roles = $(".app-from-roleIds");
                        var userIds = [];
                        for (var r in roles) {
                            if (typeof (roles[r].checked) != 'undefined') {
                                if (roles[r].checked) {
                                    userIds.push(roles[r].value);
                                }
                            }
                        }
                        tools.request({
                            url: '/plm/api/role/updateUserRole',
                            method: 'get',
                            params: {userIds: userIds.join(","), roleId: data.roleId}
                        }).done(res => {
                            if (res.code == 0) {
                                layer.msg('操作成功', {icon: 1, time: 500});
                                layer.close(index);
                            } else {
                                layer.msg(res.msg, {icon: 2, time: 500});
                            }
                        })
                    }
                });
            },
        }
        menthods.initDataTable();
        menthods.on();
    });

</script>
<style>
    .center {
        display: flex;
        align-items: center;
        justify-content: center;
        justify-self: center;
        margin-top: 6px;
    }
</style>